var md5Util = require('md5Util.js');

// const BASE_URL = "http://rap2api.taobao.org/app/mock/226303/";
const BASE_URL = "http://192.168.1.102:80/fch-back-api/gateway";
// const BASE_URL = "https://iface.fengchanhui.wizhong.com/gateway";

const API_VER = "1.0";

const ERROR_SYS = -1; //系统网络错误

var requestHandler = {
  success(res) {
    // success
  },
  fail(code, res) {
    //-1:网络失败
    //其他：逻辑失败
    // fail
  },
  complete() {
    //complete
  }
}

function GetRequest(methodName, paramData, requestHandler) {
  return request("GET", methodName, paramData, requestHandler, {})
}

function PostRequest(methodName, paramData, requestHandler) {
  return request("POST", methodName, paramData, requestHandler, {})
}

/**
 * 农技接口使用，header中新增module参数
 */
function PostRequestHeaderApp(methodName, paramData, requestHandler) {
  return request("POST", methodName, paramData, requestHandler, {
    'module': 'app'
  })
}

function request(method, methodName, paramData, requestHandler, headerParam) {
  if (!methodName) {
    return null;
  }

  paramData = paramData || {};
  if (typeof paramData == 'object') {
    if (getApp().globalData.loginCode) {
      paramData.loginId = getApp().globalData.loginCode;
    }
    paramData = JSON.stringify(paramData);
  } else {
    return null;
  }
  if (!requestHandler) {
    return null;
  }
  var url = BASE_URL
  //test
  // url = BASE_URL + methodName

  // if (methodName == 'seller.activity_find_scene1'){
  // url = "http://192.168.1.112/seller.activity_find_scene.json"
  // }
  headerParam = headerParam || {},
    headerParam['content-type'] = 'application/x-www-form-urlencoded'

  var requestTask = wx.request({
    url: url,
    method: method,
    header: headerParam,
    data: {
      ver: API_VER,
      method: methodName,
      data: paramData,
      sign: decodeSign(methodName, paramData),
    },
    success(res) {
      if (res.data.code == "0000") {
        var resultData = res.data.result
        if (resultData && (typeof resultData == 'string')) {
          resultData = JSON.parse(resultData)
        }
        requestHandler.success && requestHandler.success(resultData);
      } else {
        requestHandler.fail && requestHandler.fail(res.data.code || ERROR_SYS, res.data.msg);
      }
    },
    fail(e) {
      console.log(e.errMsg);
      requestHandler.fail && requestHandler.fail(ERROR_SYS, "网络异常..");
    },
    complete() {
      requestHandler.complete && requestHandler.complete();
    }
  })
  return requestTask;
}

function decodeSign(method, data) {
  data = data || '';
  var tmpStr = method + data;
  return md5Util.hexMD5(tmpStr).toLowerCase();
}

module.exports = {
  ERROR_SYS: ERROR_SYS,
  GetRequest: GetRequest,
  PostRequest: PostRequest,
  PostRequestHeaderApp: PostRequestHeaderApp
}